package com.fire.web.modules.all.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.fire.common.mybatis.mvc.wrapper.EntityWrapper;
import com.fire.web.modules.all.utils.TokenUtil;
import com.fire.web.modules.all.utils.WrapperUtil;
import com.fire.web.modules.all.constant.ErrorCodeConstants;
import com.fire.web.modules.all.entity.AjaxResult;
import com.fire.web.modules.all.entity.FireProprietorModel;
import com.fire.web.modules.all.entity.FireSupervisorModel;
import com.fire.web.modules.all.request.AddProprietorReq;
import com.fire.web.modules.all.request.AddSupervisorReq;
import com.fire.web.modules.all.service.IFireProprietorService;
import com.fire.web.modules.all.service.IFireSupervisorService;
import com.fire.web.modules.all.service.ISequenceService;
import com.fire.web.modules.all.service.ITMitErrorCodeService;
import com.fire.web.modules.sso.service.IOAuthService;
import com.fire.web.security.shiro.realm.UserRealm;
import com.fire.web.utils.PageRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Wrapper;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/supervisor")
public class SupervisorController extends CrudController<IFireSupervisorService, FireSupervisorModel> {
	private static final Logger LOGGER = LoggerFactory.getLogger(SupervisorController.class);

	@Autowired
	ITMitErrorCodeService errorCodeService;
	@Autowired
	IFireSupervisorService fireSupervisorService;
	@Autowired
	ISequenceService sequenceService;
	@Autowired
	private IOAuthService oAuthService;


	/**
	 * 增加业主单位
	 *
	 * @return
	 */
	@PostMapping("/addSupervisor")
	@ResponseBody
	public AjaxResult addSupervisor(AddSupervisorReq req, HttpServletRequest request, HttpServletResponse response) {
		LOGGER.info("==================新增监管单位开始==================");
		LOGGER.info(req.toString());
		AjaxResult ajaxResult;
		try {
			String token = TokenUtil.getToken(request, response);
			UserRealm.Principal principalByAccessToken = oAuthService.getPrincipalByAccessToken(token);
			String id = principalByAccessToken.getId();
			ajaxResult = fireSupervisorService.addSupervisor(req, id);
		} catch (Exception e) {
			LOGGER.error("SupervisorController.addSupervisor().error  错误为：", e);
			ajaxResult = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
		}
		//替换tips
		ajaxResult = replaceTips(ajaxResult);
		LOGGER.info("==================新增监管单位结束==================");
		return ajaxResult;
	}

	/**
	 * 更新业主单位
	 *
	 * @return
	 */
	@PostMapping("/updateSupervisor")
	@ResponseBody
	public AjaxResult updateSupervisor(AddSupervisorReq req) {
		LOGGER.info("==================更新监管单位开始==================");
		LOGGER.info(req.toString());
		AjaxResult ajaxResult;
		try {
			ajaxResult = fireSupervisorService.updateSupervisor(req);
		} catch (Exception e) {
			LOGGER.error("SupervisorController.updateSupervisor().error  错误为：", e);
			ajaxResult = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
		}
		//替换tips
		ajaxResult = replaceTips(ajaxResult);
		LOGGER.info("==================更新监管单位结束==================");
		return ajaxResult;
	}

	/**
	 * 查询所有监管单位（label/value下拉选使用）
	 *
	 * @return
	 */
	@GetMapping("/selectLabelValue/{supervisorid}")
	@ResponseBody
	public AjaxResult selectLabelValue(@PathVariable("supervisorid") String supervisorid) {
		LOGGER.info("==================查询所有监管单位下拉选开始==================");
		AjaxResult ajaxResult;
		try {
			ajaxResult = fireSupervisorService.selectLabelValue(supervisorid);
		} catch (Exception e) {
			LOGGER.error("SupervisorController.selectLabelValue().error  错误为：", e);
			ajaxResult = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
		}
		//替换tips
		ajaxResult = replaceTips(ajaxResult);
		LOGGER.info("==================查询所有监管单位下拉选结束==================");
		return ajaxResult;
	}

	/**
	 * 查询列表
	 *
	 * @return
	 */
	@Override
	@GetMapping("/page")
	public AjaxResult page(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
		AjaxResult ajaxResult;
		try {
			String token = TokenUtil.getToken(request, response);
			UserRealm.Principal principalByAccessToken = oAuthService.getPrincipalByAccessToken(token);
			String id = principalByAccessToken.getId();
			String username = principalByAccessToken.getUsername();
			//遍历参数获得查询条件
			EntityWrapper ew = WrapperUtil.getEw(params);
			//查询
			Page pageBean = null;
			String adminStr = "admin";
			if (adminStr.equals(username)) {
				pageBean = fireSupervisorService.querySupervisorListMap(PageRequest.getPage(), ew);
			} else {
				pageBean = fireSupervisorService.querySupervisorListMap(PageRequest.getPage(), ew.eq("adminid", id));
			}
			ajaxResult = new AjaxResult(ErrorCodeConstants.SUCCESS, "获取成功", pageBean, "获取成功");
		} catch (Exception e) {
			LOGGER.error("SupervisorController.page().error  错误为：", e);
			ajaxResult = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
		}
		//替换tips
		ajaxResult = replaceTips(ajaxResult);

		return ajaxResult;
	}

	/**
	 * 查询下级单位列表
	 *
	 * @return
	 */
	@GetMapping("/getSubDepartmentList")
	public AjaxResult getSubDepartmentList(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
		AjaxResult ajaxResult;
		try {
			String token = TokenUtil.getToken(request, response);
			UserRealm.Principal principalByAccessToken = oAuthService.getPrincipalByAccessToken(token);
			String username = principalByAccessToken.getUsername();
			String userId = principalByAccessToken.getId();
			EntityWrapper wrapper = new EntityWrapper();
			wrapper.eq("adminid", userId);
			List<FireSupervisorModel> list = fireSupervisorService.selectList(wrapper);
			if (list == null || list.size() == 0) {
				return new AjaxResult(ErrorCodeConstants.SUCCESS, "获取成功", "", "获取成功");
			}
			//遍历参数获得查询条件
			EntityWrapper ew = WrapperUtil.getEw(params);
			ew.and();
			for (int i = 0; i < list.size(); i++) {
				FireSupervisorModel model = list.get(i);
				ew.eq("upsuervisorid", model.getSupervisorid());
				if (i != list.size() - 1) {
					ew.or();
				}
			}
			//查询
			Page pageBean = fireSupervisorService.querySupervisorListMap(PageRequest.getPage(), ew);
			ajaxResult = new AjaxResult(ErrorCodeConstants.SUCCESS, "获取成功", pageBean, "获取成功");
		} catch (Exception e) {
			LOGGER.error("SupervisorController.getSubDepartmentList().error  错误为：", e);
			ajaxResult = new AjaxResult(ErrorCodeConstants.INTERNAL_ERROR, "系统内部错误", "系统内部错误");
		}
		//替换tips
		ajaxResult = replaceTips(ajaxResult);

		return ajaxResult;
	}


}
